from flask import Flask, jsonify, request
from flask_cors import CORS
from qwen_function_call import QwenFunctionCall
import os

app = Flask(__name__)
CORS(app)
# 初始化通义千问功能
qwen_client = QwenFunctionCall()

# 基本路由
@app.route('/')
def home():
    return jsonify({
        'message': 'Welcome to Flask Web API!',
        'status': 'success',
        'endpoints': {
            'POST /api/data': 'Submit data',
            'GET /api/users': 'Get users list',
            'POST /api/qwen/chat': 'Chat with Qwen (Function Call)',
            'GET /api/qwen/functions': 'Get available functions',
            'POST /api/qwen/function': 'Execute specific function'
        }
    })

# 通义千问聊天接口（支持 Function Call）
@app.route('/api/qwen/chat', methods=['POST'])
def qwen_chat():
    try:
        data = request.get_json()
        if not data or 'message' not in data:
            return jsonify({
                'error': 'Missing message in request body',
                'status': 'error'
            }), 400
        
        user_message = data['message']
        # 判断function_calls字段是否存在
        function_chioce = data.get('function_calls', [])
        print("获取前端传入的function",function_chioce)
        api_key = data.get('api_key') or os.getenv('DASHSCOPE_API_KEY')
        
        if not api_key:
            return jsonify({
                'error': 'API Key is required',
                'message': 'Please provide api_key in request body or set DASHSCOPE_API_KEY environment variable',
                'status': 'error'
            }), 400
        print("---开始调用大模型---")
        result = qwen_client.chat_with_functions(user_message, function_chioce, api_key)
        print("---完成大模型调用，返回---",result)
        return jsonify(result)
        
    except Exception as e:
        return jsonify({
            'error': f'Error processing chat request: {str(e)}',
            'status': 'error'
        }), 500


# 接收 POST 数据的端点
@app.route('/api/data', methods=['POST'])
def submit_data():
    try:
        data = request.get_json()
        if not data:
            return jsonify({
                'message': 'No data provided',
                'status': 'error'
            }), 400
        
        return jsonify({
            'message': 'Data received successfully',
            'status': 'success',
            'received_data': data
        })
    except Exception as e:
        return jsonify({
            'message': f'Error processing data: {str(e)}',
            'status': 'error'
        }), 500


# 获取可用函数列表
@app.route('/api/qwen/functions', methods=['GET'])
def get_qwen_functions():
    try:
        functions = qwen_client.get_function_definitions()
        return jsonify({
            'functions': functions,
            'count': len(functions),
            'status': 'success'
        })
    except Exception as e:
        return jsonify({
            'error': f'Error getting functions: {str(e)}',
            'status': 'error'
        }), 500

# 直接执行特定函数
@app.route('/api/qwen/function', methods=['POST'])
def execute_qwen_function():
    try:
        data = request.get_json()
        if not data or 'function_name' not in data or 'arguments' not in data:
            return jsonify({
                'error': 'Missing function_name or arguments in request body',
                'status': 'error'
            }), 400
        
        function_name = data['function_name']
        arguments = data['arguments']
        
        result = qwen_client.execute_function(function_name, arguments)
        return jsonify({
            'function_name': function_name,
            'arguments': arguments,
            'result': result,
            'status': 'success'
        })
        
    except Exception as e:
        return jsonify({
            'error': f'Error executing function: {str(e)}',
            'status': 'error'
        }), 500

# 健康检查端点
@app.route('/health')
def health_check():
    return jsonify({
        'status': 'healthy',
        'service': 'Flask Web API with Qwen Function Call',
        'version': '1.0.0',
        'features': ['basic_api', 'qwen_function_call']
    })

def main():
    print("Starting Flask Web API...")
    app.run(host='0.0.0.0', port=5000, debug=True)

if __name__ == "__main__":
    main()
